package chexuan.game.service.io.connection;

import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import chexuan.game.interfaces.io.connection.AbstractSocketConnection;

public class SocketConnectionCollector {

	private static Map<Integer, AbstractSocketConnection> socketConnections = new HashMap<Integer, AbstractSocketConnection>();

	private static SocketConnectionCollector instance = null;

	public static SocketConnectionCollector getInstance() {
		if (null == instance) {
			instance = new SocketConnectionCollector();
		}

		return instance;
	}

	private SocketConnectionCollector() {
	}

	public void addConnection(AbstractSocketConnection connection) {
		if (!socketConnections.containsKey(connection.getConnectionId())) {
			socketConnections.put(connection.getConnectionId(), connection);
		}
	}

	public void removeConnection(AbstractSocketConnection connection) {
		if (socketConnections.containsKey(connection)) {
			socketConnections.remove(connection.getConnectionId());
		}
	}

	public void clear() {
		socketConnections.clear();
	}

	public AbstractSocketConnection getConnection(int connectionId) {
		if (socketConnections.containsKey(connectionId)) {
			return socketConnections.get(connectionId);
		}

		return null;
	}

	public int getConnectionId(SocketChannel channel) {
		Iterator<AbstractSocketConnection> connections = socketConnections
				.values().iterator();
		while (connections.hasNext()) {
			AbstractSocketConnection abstractConnection = connections.next();
			if (abstractConnection instanceof SocketConnection) {
				SocketConnection connection = (SocketConnection) abstractConnection;
				if (connection.channelEquals(channel)) {
					return connection.getConnectionId();
				}
			}
		}

		return AbstractSocketConnection.INVALID_CONNECTION_ID;
	}
}
